package com.yidin.widget;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import com.yidin.lsc.R;

import HaoRan.ImageFilter.BlackWhiteFilter;
import HaoRan.ImageFilter.BlockPrintFilter;
import HaoRan.ImageFilter.BrickFilter;
import HaoRan.ImageFilter.BrightContrastFilter;
import HaoRan.ImageFilter.CleanGlassFilter;
import HaoRan.ImageFilter.ColorToneFilter;
import HaoRan.ImageFilter.ComicFilter;
import HaoRan.ImageFilter.EdgeFilter;
import HaoRan.ImageFilter.FeatherFilter;
import HaoRan.ImageFilter.GaussianBlurFilter;
import HaoRan.ImageFilter.InvertFilter;
import HaoRan.ImageFilter.LomoFilter;
import HaoRan.ImageFilter.PixelateFilter;

import HaoRan.ImageFilter.FilmFilter;
import HaoRan.ImageFilter.FocusFilter;

import HaoRan.ImageFilter.Gradient;

import HaoRan.ImageFilter.IImageFilter;
import HaoRan.ImageFilter.Image;

import HaoRan.ImageFilter.PaintBorderFilter;

import HaoRan.ImageFilter.SceneFilter;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;

import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.TextView;

/**
 * 图片选取和拍照功能
 * 
 * @author cola
 * 
 */
public class Carema extends Activity {
	/** Called when the activity is first created. */
	private Bitmap myBitmap;
	private byte[] mContent;
	private Button updateBtn;
	private ImageView photo;
	private Button back;
	private Button rightBtn;
	private TextView midTitl;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		final CharSequence[] items = { "相册", "拍照" };
		AlertDialog dlg = new AlertDialog.Builder(Carema.this).setTitle("选择图片")
				.setItems(items, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int item) {
						// 这里item是根据选择的方式，
						// 在items数组里面定义了两种方式，拍照的下标为1所以就调用拍照方法
						if (item == 1) {
							Intent getImageByCamera = new Intent(
									"android.media.action.IMAGE_CAPTURE");
							startActivityForResult(getImageByCamera, 1);
						} else {
							Intent getImage = new Intent(
									Intent.ACTION_GET_CONTENT);
							getImage.addCategory(Intent.CATEGORY_OPENABLE);
							getImage.setType("image/jpeg");
							startActivityForResult(getImage, 0);
						}
					}
				}).create();
		dlg.show();
		// finish();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);

		ContentResolver resolver = getContentResolver();
		/**
		 * 因为两种方式都用到了startActivityForResult方法， 这个方法执行完后都会执行onActivityResult方法，
		 * 所以为了区别到底选择了那个方式获取图片要进行判断，
		 * 这里的requestCode跟startActivityForResult里面第二个参数对应
		 */
		if (requestCode == 0) {
			try {
				if (data == null) {
					finish();
					return;
				}
				// 获得图片的uri
				Uri originalUri = data.getData();
				// 将图片内容解析成字节数组
				mContent = readStream(resolver.openInputStream(Uri
						.parse(originalUri.toString())));
				BitmapFactory.Options options = new BitmapFactory.Options();
				options.inSampleSize = 2;// 图片高宽度都为原来的二分之一，即图片大小为原来的大小的四分之一
				// 将字节数组转换为ImageView可调用的Bitmap对象
				myBitmap = getPicFromBytes(mContent, null);
				int hight = myBitmap.getHeight();
				int width = myBitmap.getWidth();
				if (hight > width) {
					if (hight > 500 && hight < 1000) {
						options.inSampleSize = 2;
					} else if (hight > 1000 && hight < 2000) {
						options.inSampleSize = 3;
					} else if (hight > 2000) {
						options.inSampleSize = 4;
					}else if (hight > 2500) {
						options.inSampleSize = 5;
					}
				}else if (width > hight ) {
					if (width > 500 && width < 1000) {
						options.inSampleSize = 2;
					} else if (width > 1000 && width < 2000) {
						options.inSampleSize = 3;
					} else if (width > 2000) {
						options.inSampleSize = 4;
					}else if (width > 2500) {
						options.inSampleSize = 5;
					}
				}

				myBitmap = getPicFromBytes(mContent, options);
				 hight = myBitmap.getHeight();
				 width = myBitmap.getWidth();
			} catch (Exception e) {
				System.out.println(e.getMessage());
			}
			init();
		} else if (requestCode == 1) {
			try {
				super.onActivityResult(requestCode, resultCode, data);
				Bundle extras = data.getExtras();
				myBitmap = (Bitmap) extras.get("data");
				if (myBitmap == null)
					return;
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				myBitmap.compress(Bitmap.CompressFormat.JPEG, 90, baos);
				mContent = baos.toByteArray();
				myBitmap = getPicFromBytes(mContent, null);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				finish();
			}
			init();
		}
	}

	private void init() {
		setContentView(R.layout.updatephotocontainer);
		// this.updateBtn = (Button) findViewById(R.id.navigationPhoto);
		this.back = (Button) findViewById(R.id.leftBtn);
		this.photo = (ImageView) findViewById(R.id.switcher);
		this.photo.setImageBitmap(myBitmap);
		this.back.setOnClickListener(backOnClickListener);
		this.midTitl = (TextView) findViewById(R.id.title);
		this.midTitl.setText(R.string.imageFilter);

		this.updateBtn = (Button) findViewById(R.id.rightBtn);
		// this.updateBtn.setBackgroundResource(R.drawable.btn_2);
		this.updateBtn.setBackgroundDrawable(null);
		this.updateBtn.setText("下一步");
		this.updateBtn.setOnClickListener(nextOnClickListener);
		ViewContainer = (ViewGroup) findViewById(R.id.photoContainer);
		this.LoadImageFilter();
	}

	public static Bitmap getPicFromBytes(byte[] bytes,
			BitmapFactory.Options opts) {
		if (bytes != null)
			if (opts != null)
				return BitmapFactory.decodeByteArray(bytes, 0, bytes.length,
						opts);
			else
				return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
		return null;
	}

	public static byte[] readStream(InputStream inStream) throws Exception {
		byte[] buffer = new byte[1024];
		int len = -1;
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		while ((len = inStream.read(buffer)) != -1) {
			outStream.write(buffer, 0, len);
		}
		byte[] data = outStream.toByteArray();
		outStream.close();
		inStream.close();
		return data;

	}

	private OnClickListener backOnClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			// if(myBitmap != null)
			// myBitmap.recycle();
			// finish();
			// new processImageTask(Carema.this, new
			// PaintBorderFilter(0x00FF00))
			// .execute();
		}

	};

	private ViewGroup ViewContainer;
	private OnClickListener nextOnClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			if (updateBtn.getText().toString().equals("下一步")) {
				updateBtn.setText(R.string.update);
				midTitl.setText(R.string.updatePhoto);
				View view = getLayoutInflater().inflate(R.layout.updatephoto,
						null);
				ViewContainer.removeAllViews();
				ViewContainer.addView(view);
				((ImageView) findViewById(R.id.updateImage))
						.setImageBitmap(myBitmap);
			}
		}

	};

	public class processImageTask extends AsyncTask<Void, Void, Bitmap> {
		private IImageFilter filter;
		private Activity activity = null;

		public processImageTask(Activity activity, IImageFilter imageFilter) {
			this.filter = imageFilter;
			this.activity = activity;
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			// textView.setVisibility(View.VISIBLE);
		}

		public Bitmap doInBackground(Void... params) {
			Image img = null;
			try {
				Bitmap bitmap = myBitmap;// BitmapFactory.decodeResource(activity.getResources(),
											// R.drawable.image);
				img = new Image(bitmap);
				if (filter != null) {
					img = filter.process(img);
					img.copyPixelsFromBuffer();
				}
				return img.getImage();
			} catch (Exception e) {
				if (img != null && img.destImage.isRecycled()) {
					img.destImage.recycle();
					img.destImage = null;
					System.gc(); // 提醒系统及时回收
				}
			} finally {
				if (img != null && img.image.isRecycled()) {
					img.image.recycle();
					img.image = null;
					System.gc(); // 提醒系统及时回收
				}
			}
			return null;
		}

		@Override
		protected void onPostExecute(Bitmap result) {
			if (result != null) {
				super.onPostExecute(result);
				photo.setImageBitmap(result);
			}
			dismissProgress();
		}
	}

	/**
	 * 加载图片filter
	 */
	private void LoadImageFilter() {
		SlowGallery gallery = (SlowGallery) findViewById(R.id.galleryFilter);
		final ImageFilterAdapter filterAdapter = new ImageFilterAdapter(
				Carema.this);
		gallery.setAdapter(new ImageFilterAdapter(Carema.this));
		gallery.setSelection(2);
		gallery.setAnimationDuration(3000);
		gallery.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long id) {
				IImageFilter filter = (IImageFilter) filterAdapter
						.getItem(position);
				new processImageTask(Carema.this, filter).execute();
				showProgress(Carema.this);
			}
		});
	}

	public class ImageFilterAdapter extends BaseAdapter {
		private class FilterInfo {
			public int filterID;
			public IImageFilter filter;

			public FilterInfo(int filterID, IImageFilter filter) {
				this.filterID = filterID;
				this.filter = filter;
			}
		}

		private Context mContext;
		private List<FilterInfo> filterArray = new ArrayList<FilterInfo>();

		public ImageFilterAdapter(Context c) {
			mContext = c;

			// v0.2
			filterArray.add(new FilterInfo(R.drawable.dp, new InvertFilter()));
			filterArray.add(new FilterInfo(R.drawable.hb,
					new BlackWhiteFilter()));// green
			filterArray.add(new FilterInfo(R.drawable.hj, new ColorToneFilter(
					Color.rgb(33, 168, 254), 192)));// purple
			filterArray.add(new FilterInfo(R.drawable.sm, new EdgeFilter()));// blue
//			filterArray
//					.add(new FilterInfo(R.drawable.rxf, new FeatherFilter()));
			filterArray.add(new FilterInfo(R.drawable.lomo, new LomoFilter()));
			//filterArray.add(new FilterInfo(R.drawable.jp, new BrickFilter()));
			filterArray.add(new FilterInfo(R.drawable.ld, new ColorToneFilter(
					0xFF0000, 192)));

			filterArray.add(new FilterInfo(R.drawable.ml, new ColorToneFilter(
					0x00FF00, 192)// 此处会生成原图效果
					));
		}

		public int getCount() {
			return filterArray.size();
		}

		public Object getItem(int position) {
			return position < filterArray.size() ? filterArray.get(position).filter
					: null;
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			Bitmap bmImg = BitmapFactory
					.decodeResource(mContext.getResources(),
							filterArray.get(position).filterID);
			int width = 100;// bmImg.getWidth();
			int height = 100;// bmImg.getHeight();
			bmImg.recycle();
			ImageView imageview = new ImageView(mContext);
			imageview.setImageResource(filterArray.get(position).filterID);
			imageview.setLayoutParams(new Gallery.LayoutParams(width, height));
			imageview.setScaleType(ImageView.ScaleType.FIT_CENTER);// 设置显示比例类型
			return imageview;
		}
	};

	private ProgressDialog m_ProgressDialog;

	public void showProgress(Context context) {

		if (null == m_ProgressDialog) {
			m_ProgressDialog = new ProgressDialog(context);
			m_ProgressDialog.setMessage("正在处理中，请稍候...");
			m_ProgressDialog.setCancelable(true);
		}

		m_ProgressDialog.show();
	}

	public void dismissProgress() {

		if (null != m_ProgressDialog && m_ProgressDialog.isShowing()) {
			m_ProgressDialog.dismiss();
		}
	}
}